package com.xcity.game.combat.skill.impl;

import java.util.List;

import com.xcity.game.combat.Action;
import com.xcity.game.combat.ActionEffect;
import com.xcity.game.combat.CombatUtils;
import com.xcity.game.combat.Round;
import com.xcity.game.combat.skill.CombatSkill;
import com.xcity.game.combat.unit.CombatUnit;
import com.xcity.game.common.GameStaticConfig;
import com.xcity.game.skill.Skill;

/**
 * 株连九族<br/>
 * 攻击目标{0}次，每次造成{1}%的技能伤害，若目标在攻击中死亡则额外对全体敌方造成{2}%技能伤害
 * @author yang.li
 *
 */
public class COMBAT_SKILL_90117 extends CombatSkill {

	public COMBAT_SKILL_90117(Skill skill) {
		super(skill);
	}

	@Override
	public void calcDamage(Action action) {
		CombatUnit source = action.unit;
		CombatUnit target = action.target.getDefenseUnit(source.getIndex());
		if (target != null) {
			// 单体伤害
			int count = (int) skill.getParameter(0);
			float rate = skill.getParameter(1) / GameStaticConfig.percentBase;
			for (int i = 0; i < count; i++) { // 攻击count次
				if (target.isDied()) {
					// 全体伤害
					damageAll(action);
					break;
				}
				ActionEffect eff = newActionEffect(action, source, target);
				CombatUtils.calcMagicAttack(eff, rate);
			}
		}
	}
	
	private void damageAll(Action action) {
		CombatUnit source = action.unit;
		List<CombatUnit> targets = action.target.all();
		float rate = skill.getParameter(2) / GameStaticConfig.percentBase;
		Action act = null;
		for (int i = 0; i < targets.size(); i++) {
			CombatUnit u = targets.get(i);
			if (!u.isDied()) {
				if (act == null) {
					act = newAction(action, source);
				}
				ActionEffect eff = act.addTarget(u);
				CombatUtils.calcMagicAttack(eff, rate);
			}
		}
	}
	
	private static Action newAction(Action base, CombatUnit source) {
		if (base.getEffects() == null || base.getEffects().isEmpty()) {
			return base;
		}
		// 产生一个新的动作并加入回合
		Round round = base.ref();
		Action action = new Action(source);
		round.add(action);
		return action;
	}
	
	private static ActionEffect newActionEffect(Action base, CombatUnit source, CombatUnit target) {
		Action action = newAction(base, source);
		return action.addTarget(target);
	}

}
